﻿using System;
using System.IO;

namespace AsyncLock
{
    class Program
    {
        readonly StreamWriter StreamWriter;
        readonly string fillText = " asdkfjklajsrtlekjszdfhslktrjheklshsdklfgvsdk;ljfl;ktjerklgfdklsalsjdlkf;jesrkotjs;ldfk;lsdkjgousdf98iuewroipt5uj34otjgsldkfjoidstuo4i53wjtglrk;aekjg;lskdfjg;jkajsdf;l";
        readonly AsyncLock asyncLock;

        public Program()
        {
            string fileName = "test";
            FileInfo fileInfo = new FileInfo($"{fileName}.log");
            StreamWriter = fileInfo.AppendText();
            StreamWriter.AutoFlush = false;
            asyncLock = new AsyncLock();

        }

        public async void WriteAsync(string msg)
        {
            using (var releaser = await asyncLock.LockAsync())
            {
                await StreamWriter.WriteLineAsync(msg + fillText);
            }
        }

        public void Flush()
        {
            StreamWriter.Flush();
        }

        public void Close()
        {
            StreamWriter.Close();
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Program program = new Program();
            program.WriteAsync("");
            program.WriteAsync(DateTime.Now.ToString());

            for (int i = 10; i > 0; i--)
                program.WriteAsync(DateTime.Now.Ticks.ToString());
            program.Close();
        }
    }
}
